import { component$, useSignal } from '@builder.io/qwik';
import { Form, routeAction$, routeLoader$, z, zod$ } from '@builder.io/qwik-city';
import { getUserAccount, getUserId } from '~/server/authn';
import Avatar from '~/components/ui/Avatar';
import { db } from '~/server/db';
import { type UserInfo } from '@prisma/client';
import Button from '~/components/ui/Button';
import Input from '~/components/ui/Input';
import { userInfoService } from '~/server/service/user-info-service';

export const useLoader = routeLoader$(async (requestEvent) => {
  const userId = getUserId(requestEvent);
  const userAccount = getUserAccount(requestEvent);
  const userInfo = await userInfoService.findByUserId(db, userId);
  return {
    userId,
    userAccount,
    userInfo: userInfo || ({} as UserInfo),
  };
});

export const useSaveUserInfoAction = routeAction$(
  async (props, requestEvent) => {
    const userId = getUserId(requestEvent);

    await db.$transaction(async (tx) => {
      const now = new Date();
      const userInfo = await tx.userInfo.findFirst({ where: { userId } });
      if (userInfo) {
        await tx.userInfo.update({
          where: { userId },
          data: {
            nickname: props.nickname,
            description: props.description,
            updateTime: now,
          },
        });
      } else {
        await tx.userInfo.create({
          data: {
            userId,
            nickname: props.nickname,
            avatar: '',
            description: props.description,
            createTime: now,
            updateTime: now,
          },
        });
      }
    });
  },
  zod$(
    z.object({
      nickname: z.string().max(20, { message: '昵称最多20个字符' }),
      description: z.string().max(200, { message: '描述最多200个字符' }),
    })
  )
);

export default component$(() => {
  const auth = useLoader();
  const saveUserInfo = useSaveUserInfoAction();
  const editable = useSignal(false);

  const { userAccount, userInfo } = auth.value;

  return (
    <div>
      <div class="flex gap-4">
        <Avatar src={userInfo.avatar || '/imgs/charlotte.png'} sizing="lg" />
        {editable.value ? (
          <Form
            class="flex-1 flex flex-col gap-1"
            action={saveUserInfo}
            onSubmitCompleted$={() => {
              editable.value = false;
            }}
            spaReset
          >
            <div>
              <Input type="text" sizing="sm" name="nickname" placeholder="昵称" block value={userInfo.nickname || ''} />
            </div>
            <div>
              <Input
                type="text"
                sizing="sm"
                name="description"
                placeholder="描述"
                block
                value={userInfo.description || ''}
              />
            </div>
            <div class="flex gap-1">
              <Button sizing="sm" onClick$={() => (editable.value = false)}>
                取消
              </Button>
              {/* TODO: 保存的时候好像会闪一下 */}
              {/* TODO: csrf */}
              <Button sizing="sm" varient="primary">
                保存
              </Button>
            </div>
          </Form>
        ) : (
          <div class="flex-1 flex flex-col justify-center">
            <div class="text-xl text-kq-900 font-bold group/my-nickname">
              {userInfo.nickname || '佚名'}&nbsp;
              <small
                class="hidden group-hover/my-nickname:inline text-sm cursor-pointer"
                onClick$={() => (editable.value = true)}
              >
                ✏️
              </small>
            </div>
            <div class="text-sm text-kq-800 italic">{userInfo.description || '心之所向，日复一日，必有精进。'}</div>
            <div class="text-xs text-kq-400 mt-2">{userAccount.createTime.toLocaleString('zh-CN')}</div>
          </div>
        )}
      </div>
    </div>
  );
});
